package com.cll.learn.monitor.filter;

import com.cll.learn.monitor.bean.MethodInvokeInfo;
import com.cll.learn.monitor.util.TopPercentileUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2020/10/10 13:34
 */
@Activate(group = CommonConstants.CONSUMER)
public class InvokeTimeFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(InvokeTimeFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            long startTime = System.currentTimeMillis();
            Result invoke = invoker.invoke(invocation);
            long endTime = System.currentTimeMillis();

            long executionTime = endTime - startTime;
            if (invoke.getException() instanceof Exception) {
                throw new Exception(invoke.getException());
            }
            String methodName = invocation.getMethodName();
            List<MethodInvokeInfo> methodInvokeInfoList = TopPercentileUtil.METHOD_INVOKE_INFO_MAP.get(methodName);
            if (CollectionUtils.isEmpty(methodInvokeInfoList)) {
                methodInvokeInfoList = new ArrayList<>(0);
                TopPercentileUtil.METHOD_INVOKE_INFO_MAP.put(methodName, methodInvokeInfoList);
            }
            methodInvokeInfoList.add(new MethodInvokeInfo(methodName, executionTime, endTime));
            return invoke;
        } catch (Exception e) {
            LOGGER.error("***** 执行抛出异常" + e.getMessage(), e);
            return null;
        }
    }
}
